package com.canbot.u05.activity.agenda

import android.content.Context
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.agenda.adapter.AgendaHomeAdapter
import com.canbot.u05.activity.agenda.bean.AgendaBean
import com.canbot.u05.activity.agenda.calendar.dataIsFull
import com.canbot.u05.activity.agenda.calendar.dateToWeek
import com.canbot.u05.activity.agenda.calendar.getDate
import com.canbot.u05.activity.agenda.calendar.getWeekToDate
import com.canbot.u05.activity.agenda.dao.AgendaDataTable
import com.canbot.u05.activity.agenda.dao.AgendaDateTable
import com.canbot.u05.activity.agenda.dialog.DateDialog
import com.canbot.u05.activity.agenda.dialog.TipDialog
import com.canbot.u05.activity.agenda.interfaces.IAgendaHomeLisenter
import com.canbot.u05.activity.agenda.interfaces.IDateSelect
import com.canbot.u05.activity.presidemode.newcode.BaseHostActivity
import com.canbot.u05.activity.presidemode.newcode.bean.NetLoadUtil
import com.canbot.u05.activity.presidemode.newcode.interfaces.IResponse
import com.canbot.u05.utils.PathConst
import kotlinx.android.synthetic.main.activity_agenda_home_list.*
import kotlinx.android.synthetic.main.activity_agenda_home_loading.*
import java.util.*
import kotlin.collections.ArrayList

/**
 * @author yinxiaowei
 * @date 2019/5/31
 */
class AgendaHomeActivity : BaseHostActivity() {
    private val TAG = AgendaHomeActivity::class.java.simpleName
    private var agendaHomeAdapter: AgendaHomeAdapter? = null
    private lateinit var context: Context
    private val agendaBeanList = ArrayList<AgendaDataTable>() // 当前日期下的所有的日程
    private var currentAgendaDateTable: AgendaDateTable = AgendaDateTable() //当前日期下日程Bean
    private val voiceEmpty = arrayOf(
            arrayOf("${PathConst.AGENDA_VOICE_DIR}rccj_gzrc_u05_001.mp3", "30"),
            arrayOf("${PathConst.AGENDA_VOICE_DIR}rccj_gzrc_u05_002.mp3", "30"))

    override fun initEventData() {
        context = this
        initView()
        loadDataFromServer()
    }

    override fun onDestroy() {
        super.onDestroy()
        AgendaTypeActivity.mAgendaTypeBeanList.clear()
    }

    /**
     * 从服务器加载数据
     */
    private fun loadDataFromServer() {
        showLoadingDialog(getString(R.string.load_hint))
        NetLoadUtil.loadAgendaTask(this, Calendar.getInstance().timeInMillis, object : IResponse<String> {
            override fun onSucusse(result: String) {
                dismissDialog()
                if (TextUtils.isEmpty(result)) {
                    showEmptyView()
                } else {
                    agendaTableList = JSON.parseArray(result, AgendaDateTable::class.java)
                    agendaTableList = agendaTableList.filter {
                        it.agendaDataTableList.size > 0
                    }.toMutableList()
                    if (agendaTableList.size > 0) {
                        showListView()
                    } else {
                        showEmptyView()
                    }
                }
            }

            override fun onFailuer(result: String) {
                dismissDialog()
                showToast(result)
                if (isDebug) {
                    showEmptyView()
                }
            }
        })
    }

    private lateinit var listView: View
    private lateinit var emptyView: View
    private fun initView() {
        listView = LayoutInflater.from(this).inflate(R.layout.activity_agenda_home_list, null, false)
        listView.layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
        listView.visibility = View.GONE
        container_layout.addView(listView)
        initRecycleView()

        emptyView = LayoutInflater.from(this).inflate(R.layout.activity_agenda_home_empty, null, false)
        emptyView.layoutParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
        emptyView.visibility = View.GONE
        container_layout.addView(emptyView)
    }

    private fun showListView() {
        runOnUiThread {
            tv_date.visibility = View.VISIBLE
            emptyView.visibility = View.GONE
            listView.visibility = View.VISIBLE
            swithDateShow(0, false)
        }
    }

    /**
     * 显示指定日期的所有日程
     */
    private fun swithDateShow(index: Int, boolean: Boolean) {
        Log.e(TAG, "swithDateShow ====  $index")
        if (index < 0) { // 没有日程
            if (selectDate != null && !TextUtils.isEmpty(selectDate)) {
                tv_date.text = selectDate
            }
            tv_agenda_list_count.text = String.format(getString(R.string.agenda_list_count), 0)
            agendaBeanList.clear()
            agendaHomeAdapter?.notifyDataSetChanged()
        } else {
            agendaTableList.apply {
                currentAgendaDateTable = this[index]
                showTitleDate(boolean)
                mergerCurrentAgendaDate()
                tv_agenda_list_count.text = String.format(getString(R.string.agenda_list_count), agendaBeanList.size)
                agendaBeanList.sortBy {
                    it.agendaBean
                }
                agendaHomeAdapter?.notifyDataSetChanged()
            }
        }
        selectDate = null
    }

    private fun mergerCurrentAgendaDate() {
        agendaBeanList.clear()
        Log.e(TAG, "1   $currentAgendaDateTable")
        // 首先将当期的添加进去
        currentAgendaDateTable.agendaDataTableList.forEach {
            agendaBeanList.add(it)
        }
        if (currentAgendaDateTable.week == -1) { // 当前显示日期
            agendaTableList.forEach {
                Log.e(TAG, "2   $it")
                if (it.week != -1) { // 只比较星期
                    if (currentAgendaDateTable.date == getWeekToDate(it.week)) {
                        for (agendaDataTable in it.agendaDataTableList) {
                            agendaBeanList.add(agendaDataTable)
                        }
                    }
                }
            }
        } else {
            var date = selectDate
            if (selectDate == null) {
                date = getWeekToDate(currentAgendaDateTable.week) //当前是星期
            }
            agendaTableList.forEach {
                Log.e(TAG, "4   $it   $date")
                if (it.date == date) { // 只比较日期
                    for (agendaDataTable in it.agendaDataTableList) {
                        agendaBeanList.add(agendaDataTable)
                    }
                }
            }
        }
    }

    private fun showTitleDate(boolean: Boolean) {
        if (boolean) {
            tv_date.text = selectDate
        } else {
            if (currentAgendaDateTable.week == -1) {
                tv_date.text = currentAgendaDateTable.date
            } else {
                tv_date.text = getWeekToDate(currentAgendaDateTable.week)
            }
        }
    }

    private fun showEmptyView() {
        runOnUiThread {
            emptyView.visibility = View.VISIBLE
            listView.visibility = View.GONE
            playRandomVoiceWithEmotion(voiceEmpty)
        }
    }

    private fun initRecycleView() {
        recycleView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        agendaHomeAdapter = agendaBeanList.let {
            AgendaHomeAdapter(it, this, object : IAgendaHomeLisenter {
                override fun onEdit(pos: Int) {
                    gotoActivityForResult(AgendaCreateActivity::class.java, REQUEST_EDIT, agendaBeanList[pos])
                }

                override fun onDelete(pos: Int) {
                    val tipDialog = TipDialog(context, String.format(getString(R.string.agenda_delete), it[pos].agendaBean.agendaType.type))
                    tipDialog.setiDialogBtnLisenter {
                        showLoadingDialog(getString(R.string.delete))
                        NetLoadUtil.deleteAgendaTask(context, agendaBeanList[pos], object : IResponse<String> {
                            override fun onSucusse(result: String?) {
                                dismissDialog()
                                //deleteDateLocal(currentAgendaDateTable.agendaDataTableList[pos])
                                //updateByDelete(pos)
                                runOnUiThread { loadDataFromServer() }
                            }

                            override fun onFailuer(result: String?) {
                                dismissDialog()
                                showToast(getString(R.string.delete_failed))
                            }
                        })
                    }
                    tipDialog.show()
                }
            })
        }
        recycleView?.adapter = agendaHomeAdapter
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        when (requestCode) {
            REQUEST_ADD, REQUEST_EDIT -> {
                val agendaBean: AgendaBean? = data.getSerializableExtra(DATA) as AgendaBean?
                agendaBean?.let {
                    if (TextUtils.isEmpty(dataIsFull(it))) { // 这里重新加载数据
                        loadDataFromServer()
                    }
                }
            }
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_agenda_home_loading
    }

    fun back(view: View?) {
        finish()
    }

    override fun onBackPressed() {
        back(null)
    }

    fun newTask(view: View) {
        gotoActivityForResult(AgendaCreateActivity::class.java, REQUEST_ADD)
    }

    /**
     * 根据日期去加载对应那一天的所有工作日程（分日期加载）
     */
    fun switchDate(view: View) {
        showDateDialog()
    }

    // 选择要显示的日期
    private var selectDate: String? = null

    private fun showDateDialog() {
        val dateDialog = DateDialog(this, false, true, object : IDateSelect {
            override fun onSelect(isSelect: Boolean, data: Calendar) {
                if (isSelect) {
                    selectDate = getDate(data.timeInMillis)
                } else {
                    selectDate = null
                }
            }
        })
        dateDialog.setiDialogBtnLisenter {
            if (selectDate != null) {
                if (tv_date.text != selectDate) {
                    for (index in agendaTableList.indices) {
                        if (selectDate == agendaTableList[index].date) {// 先比较日期
                            swithDateShow(index, false)
                            return@setiDialogBtnLisenter
                        } else {
                            if (agendaTableList[index].week != -1) {
                                if (dateToWeek(selectDate!!) == agendaTableList[index].week) {
                                    swithDateShow(index, true)
                                    return@setiDialogBtnLisenter
                                }
                            }
                        }
                    }
                    // 如果该日期下没有任何日程
                    swithDateShow(-1, false)
                }
            }
        }
        dateDialog.show()
    }

    companion object {
        private val TAG = AgendaHomeActivity::class.java.simpleName
        var agendaTableList: MutableList<AgendaDateTable> = ArrayList()
    }

}
